#!/bin/bash

# 应用名称
appName="$1"

# 应用PID
pid=

# 检测PID
function checkPid() {
        echo "正在检测应用PID中......"
	pid=`ps -ef| grep ${appName}.jar| grep -v "grep"| awk '{print $2}'`
        echo $appName"的PID为："$pid
}

# 停止应用
function stopApp() {
        echo "正在停止应用..."
        #echo "当前PID为："$pid

        if [ -n "$pid" ]; then
            echo "正在杀死进程："${pid}
	    kill -9 ${pid}
            echo "杀死中..."
            sleep 5
        else
            echo "当前应用未运行..."
        fi
}

# 备份旧的应用包
function backup() {
        echo "正在备份应用旧包..."
	# 获取系统日期
	currentDateTime=$(date +%Y%m%d%H%M%S)
	mkdir /opt/backup/xinfeng/$appName/$currentDateTime
	mv /opt/app/xinfeng/$appName/${appName}.jar /opt/backup/xinfeng/$appName/$currentDateTime/
        #mv /opt/app/xinfeng/$appName/nohup /opt/backup/xinfeng/$appName/$currentDateTime/
}

# 复制应用启动包
function copy() {
        echo "正在复制应用新包...."
	cp /opt/deploy/jar/${appName}.jar /opt/app/xinfeng/$appName
}

# 启动应用
function startup() {
        echo "即将启动应用..."
	cd /opt/app/xinfeng/$appName/
	java -jar ${appName}.jar > nohup.out &
        echo "启动中...."
        sleep 5
        echo "启动完成++++++++"
}

# 自动部署
function autoDeploy() {
        echo "开始自动部署应用：${appName}...."
	checkPid
	stopApp
	backup
	copy
	startup
        echo "已完成自动部署应用：${appName} ==============="
}

# 环境准备
source /etc/profile

# 开始自动部署
autoDeploy
